<?php

App::uses('AppModel', 'Model');

class Offer extends AppModel {
    
    public $order = 'Offer.id desc';
    
    public $validate = array(
        'location_id' => array(
            'rule'    => 'notEmpty',
            'message' => 'Morate odabrati Lokaciju'
        ),
        'client_id' => array(
            'rule'    => 'notEmpty',
            'message' => 'Morate odabrati Klijenta'
        )
    );
    
    public $belongsTo = array( 'Client', 'Campaign' );
    
    public $hasAndBelongsToMany = array(
        'Location' => array ( 'joinTable' => 'offers_locations' )
    );
    public $hasMany   = array(
        'OffersLocation' => array( 'dependent' => true )
    );
    
    public function afterFind($records, $primary=false) {
        if(! empty($records)) {
            foreach ($records as &$row) {
                if (empty($row['Campaign'])) {
                    continue;
                }
                
                if (! $row['Campaign']['id']) {
                    $row['Campaign'] = array();
                }
                
                // TAX
                $row['Tax'] = array();
                $min = 0;
                if (! empty($row['OffersLocation']) && !empty($row['OffersLocation'][0]['Tax'])) {
                    foreach ($row['OffersLocation'] as $offLoc) {
                        $time = strtotime($offLoc['start']);
                        if ($min==0 || $min>$time) {
                            $min = $time;
                            $row['Tax'] = $offLoc['Tax'];
                        }
                    }
                }
            }
        }
        
        return $records;
    }

    public function cleanRelationsData() {
        if ($this->id) {
            $this->OffersLocation->deleteAll(array('OffersLocation.offer_id' => $this->id));
        }
    }
}
